

#include <sys/socket.h>
#include "esp_log.h"
#include "esp_netif.h"
#include <errno.h>

extern int sock;
extern void canWrite(uint32_t frame_id, uint8_t dlc, uint8_t* frame_data);
extern void canRead(uint32_t *frame_id, uint8_t *dlc, uint8_t* frame_data);

void display(uint8_t *stream_data, int len)
{
    printf("tcp recv: ");
    for (int i=0; i<=len-1; i++) {
        printf("%x ", stream_data[i]);
    }
    printf("\n");
}


void tcp_to_can()
{
    static char rx_buffer[128];
    while (1) {
        int len = recv(sock, rx_buffer, sizeof(rx_buffer) - 1, 0);
        // Error occurred during receiving
        if (len < 0) {
            printf("recv failed: errno %d\n", errno);
            vTaskDelay(pdMS_TO_TICKS(2000));
            continue;
        }
        // Data received
        else {

            rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
            uint32_t frame_id = rx_buffer[0] << (8*3) |
                                rx_buffer[1] << (8*2) |
                                rx_buffer[2] << (8*1) |
                                rx_buffer[3] << (8*0) ;
            uint8_t dlc = rx_buffer[4];
            uint8_t data[8] = {
                rx_buffer[5], rx_buffer[6], rx_buffer[7], rx_buffer[8],
                rx_buffer[9], rx_buffer[10], rx_buffer[11], rx_buffer[12]
            };
            canWrite(frame_id, dlc, data);
        }
    }
}


void can_to_tcp()
{
    uint32_t frame_id;
    uint8_t dlc;
    uint8_t frame_data[8];
    
    static char tcp_tx_buffer[128];

    while (1) {
        memset(frame_data, 0, 8);
        
        canRead(&frame_id, &dlc, &frame_data);
        // printf("can 收到\n");

        tcp_tx_buffer[0] = (frame_id>>(8*3)) & 0xff;
        tcp_tx_buffer[1] = (frame_id>>(8*2)) & 0xff;
        tcp_tx_buffer[2] = (frame_id>>(8*1)) & 0xff;
        tcp_tx_buffer[3] = (frame_id>>(8*0)) & 0xff;
        //
        tcp_tx_buffer[4] = dlc;
        //
        for (int i=0; i<=7; i++) {
            tcp_tx_buffer[5+i] = frame_data[i];
        }

        send(sock, tcp_tx_buffer, 13, 0);  
    }
}

